import store from '@/store'
import { Message } from 'element-ui'
import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const router = new VueRouter({
  routes: [
    { path: '/login', component: () => import('@/views/login/index.vue') },
    {
      path: '/',
      redirect: '/dashboard',
      component: () => import('@/views/layout/index.vue'),
      children: [
        // 这里用相对路径，因为是layout的孩子，会自动拼接上父级路由
        { path: 'article', component: () => import('@/views/layout/article/index.vue') },
        { path: 'dashboard', component: () => import('@/views/layout/dashboard/index.vue') }
      ]
    }
  ]
})

const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location, onResolve, onReject) {
  if (onResolve || onReject) { return originalPush.call(this, location, onResolve, onReject) }
  return originalPush.call(this, location).catch((err) => err)
}

// 前置守卫
// 如果是白名单或者有token就放行，否则跳转在登录页
const pathArr = ['/login']
const token = store.state.user.token
router.beforeEach((to, from, next) => {
  if (token || pathArr.includes(to.path)) {
    next()
  } else {
    next('/login')
    Message.warning('请您登录')
  }
})

export default router
